<template>
  <div class="question-category-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">题目分类</h1>
      <p class="page-subtitle">按类别浏览不同类型的题目，系统化学习提升</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 主要内容 -->
    <div v-else class="category-content">
      <!-- 统计概览 -->
      <div class="stats-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon total">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ totalQuestions }}</div>
                  <div class="stat-label">总题目数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon categories">
                  <el-icon><Folder /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ categories.length }}</div>
                  <div class="stat-label">分类数量</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon solved">
                  <el-icon><Check /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ solvedQuestions }}</div>
                  <div class="stat-label">已解题数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon accuracy">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ accuracyRate }}%</div>
                  <div class="stat-label">正确率</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分类筛选 -->
      <div class="filter-section">
        <el-card class="filter-card">
          <div class="filter-content">
            <div class="filter-left">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索分类名称"
                prefix-icon="Search"
                class="search-input"
                @input="handleSearch"
              />
            </div>
            <div class="filter-right">
              <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
                <el-option label="按题目数量" value="questionCount" />
                <el-option label="按名称" value="name" />
                <el-option label="按创建时间" value="createdAt" />
              </el-select>
              <el-button @click="resetFilter" class="reset-btn">重置</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分类列表 -->
      <div class="categories-section">
        <div class="categories-grid">
          <div 
            v-for="category in filteredCategories" 
            :key="category.id" 
            class="category-card"
            @click="navigateToCategory(category)"
          >
            <div class="category-header">
              <div class="category-icon">
                <el-icon><component :is="getCategoryIcon(category.name)" /></el-icon>
              </div>
              <div class="category-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="toggleFavorite(category)"
                  class="favorite-btn"
                >
                  <el-icon :class="{ 'favorited': category.isFavorite }">
                    <Star />
                  </el-icon>
                </el-button>
              </div>
            </div>
            
            <div class="category-content">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-description">{{ category.description || '暂无描述' }}</p>
              
              <div class="category-stats">
                <div class="stat-item">
                  <span class="stat-value">{{ category.questionCount || 0 }}</span>
                  <span class="stat-label">题目</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ category.solvedCount || 0 }}</span>
                  <span class="stat-label">已做</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ category.accuracy || 0 }}%</span>
                  <span class="stat-label">正确率</span>
                </div>
              </div>
              
              <div class="category-progress">
                <el-progress 
                  :percentage="getProgressPercentage(category) || 0" 
                  :stroke-width="6"
                  :show-text="false"
                />
                <span class="progress-text">{{ getProgressPercentage(category) || 0 }}% 完成</span>
              </div>
            </div>
            
            <div class="category-footer">
              <el-button type="primary" size="small" class="start-btn">
                开始练习
              </el-button>
              <el-button type="text" size="small" @click.stop="viewDetails(category)">
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredCategories.length === 0" class="empty-state">
        <el-empty description="没有找到相关分类">
          <el-button type="primary" @click="resetFilter">重置筛选</el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分类详情模态框 -->
    <el-dialog 
      v-model="showDetailModal" 
      :title="selectedCategory?.name" 
      width="800px"
      class="category-detail-modal"
    >
      <div v-if="selectedCategory" class="category-detail-content">
        <div class="detail-header">
          <div class="detail-icon">
            <el-icon><component :is="getCategoryIcon(selectedCategory.name)" /></el-icon>
          </div>
          <div class="detail-info">
            <h3>{{ selectedCategory.name }}</h3>
            <p>{{ selectedCategory.description || '暂无描述' }}</p>
          </div>
        </div>
        
        <div class="detail-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-stat">
                <div class="stat-number">{{ selectedCategory.questionCount || 0 }}</div>
                <div class="stat-label">总题目数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-stat">
                <div class="stat-number">{{ selectedCategory.solvedCount || 0 }}</div>
                <div class="stat-label">已做题目</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-stat">
                <div class="stat-number">{{ selectedCategory.accuracy || 0 }}%</div>
                <div class="stat-label">正确率</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <div class="detail-actions">
          <el-button type="primary" @click="startPractice(selectedCategory)">
            开始练习
          </el-button>
          <el-button @click="viewQuestions(selectedCategory)">
            查看题目
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getQuestionCategories } from '@/api/question';

const router = useRouter();

// 响应式数据
const loading = ref(false);
const searchKeyword = ref('');
const sortBy = ref('questionCount');
const showDetailModal = ref(false);
const selectedCategory = ref<any>(null);

// 统计数据
const totalQuestions = ref(0);
const solvedQuestions = ref(0);
const accuracyRate = ref(0);

// 分类数据
interface CategoryType {
  id: number;
  name: string;
  description: string;
  questionCount: number;
  solvedCount: number;
  accuracy: number;
  isFavorite: boolean;
  createdAt: string;
  updatedAt: string;
}

const categories = ref<CategoryType[]>([]);

// 计算属性
const filteredCategories = computed(() => {
  let filtered = [...categories.value];
  
  // 搜索筛选
  if (searchKeyword.value) {
    filtered = filtered.filter(category => 
      category.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (category.description && category.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    );
  }
  
  // 排序
  switch (sortBy.value) {
    case 'questionCount':
      filtered.sort((a, b) => (b.questionCount || 0) - (a.questionCount || 0));
      break;
    case 'name':
      filtered.sort((a, b) => a.name.localeCompare(b.name));
      break;
    case 'createdAt':
      filtered.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
      break;
  }
  
  return filtered;
});

// 获取分类图标
const getCategoryIcon = (categoryName: string) => {
  const iconMap: Record<string, string> = {
    '行测': 'BarChart',
    '申论': 'Document',
    '面试': 'User',
    '常识判断': 'Star',
    '言语理解': 'ChatDotSquare',
    '数量关系': 'Calculator',
    '判断推理': 'Box',
    '资料分析': 'PieChart',
    '法律常识': 'Scale',
    '时政热点': 'TrendCharts'
  };
  
  for (const [key, icon] of Object.entries(iconMap)) {
    if (categoryName.includes(key)) {
      return icon;
    }
  }
  
  return 'Folder';
};

// 获取进度百分比
const getProgressPercentage = (category: CategoryType) => {
  if (!category.questionCount || category.questionCount === 0) return 0;
  const percentage = Math.round((category.solvedCount || 0) / category.questionCount * 100);
  return Math.max(0, Math.min(100, percentage)); // 确保在0-100范围内
};

// 加载分类数据
const loadCategories = async () => {
  try {
    loading.value = true;
    console.log('开始加载题目分类数据...');
    
    const response = await getQuestionCategories();
    console.log('获取到的分类数据:', response);
    
    // 数据转换和增强
    categories.value = response.map((item: any) => ({
      id: item.id,
      name: item.name,
      description: item.description || '',
      questionCount: item.questionCount || 0,
      solvedCount: item.solvedCount || 0,
      accuracy: item.accuracy || 0,
      isFavorite: false,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt
    }));
    
    console.log('处理后的分类数据:', categories.value);
    
    // 计算统计数据
    totalQuestions.value = categories.value.reduce((sum, cat) => sum + (cat.questionCount || 0), 0);
    solvedQuestions.value = categories.value.reduce((sum, cat) => sum + (cat.solvedCount || 0), 0);
    accuracyRate.value = solvedQuestions.value > 0 ? 
      Math.round(categories.value.reduce((sum, cat) => sum + (cat.accuracy || 0), 0) / categories.value.length) : 0;
    
    console.log('统计数据:', {
      totalQuestions: totalQuestions.value,
      solvedQuestions: solvedQuestions.value,
      accuracyRate: accuracyRate.value
    });
    
    ElMessage.success('分类数据加载成功');
      
  } catch (error) {
    console.error('加载分类数据失败', error);
    ElMessage.error('加载分类数据失败，请稍后重试');
    
    // 清空数据，显示空状态
    categories.value = [];
    totalQuestions.value = 0;
    solvedQuestions.value = 0;
    accuracyRate.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

// 排序处理
const handleSortChange = () => {
  // 排序逻辑已在计算属性中处理
};

// 重置筛选
const resetFilter = () => {
  searchKeyword.value = '';
  sortBy.value = 'questionCount';
};

// 导航到分类
const navigateToCategory = (category: CategoryType) => {
  router.push(`/search-question?category=${category.id}`);
};

// 切换收藏
const toggleFavorite = (category: CategoryType) => {
  category.isFavorite = !category.isFavorite;
  ElMessage.success(category.isFavorite ? '已收藏' : '已取消收藏');
};

// 查看详情
const viewDetails = (category: CategoryType) => {
  selectedCategory.value = category;
  showDetailModal.value = true;
};

// 开始练习
const startPractice = (category: CategoryType) => {
  router.push(`/search-question?category=${category.id}&mode=practice`);
  showDetailModal.value = false;
};

// 查看题目
const viewQuestions = (category: CategoryType) => {
  router.push(`/search-question?category=${category.id}`);
  showDetailModal.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
});
</script>

<style lang="scss" scoped>
.question-category-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }
}

.loading-container {
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-overview {
  margin-bottom: 30px;

  .stat-card {
    border-radius: 12px;
    overflow: hidden;
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }

  .stat-content {
    display: flex;
    align-items: center;
    padding: 20px;

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      font-size: 24px;
      color: white;

      &.total {
        background: linear-gradient(135deg, #667eea, #764ba2);
      }

      &.categories {
        background: linear-gradient(135deg, #f093fb, #f5576c);
      }

      &.solved {
        background: linear-gradient(135deg, #4facfe, #00f2fe);
      }

      &.accuracy {
        background: linear-gradient(135deg, #43e97b, #38f9d7);
      }
    }

    .stat-info {
      .stat-number {
        font-size: 28px;
        font-weight: 700;
        color: #1f2937;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 14px;
        color: #6b7280;
      }
    }
  }
}

.filter-section {
  margin-bottom: 30px;

  .filter-card {
    border-radius: 12px;
    overflow: hidden;
  }

  .filter-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;

    .filter-left {
      flex: 1;
      margin-right: 20px;

      .search-input {
        max-width: 400px;
      }
    }

    .filter-right {
      display: flex;
      align-items: center;
      gap: 15px;

      .reset-btn {
        margin-left: 10px;
      }
    }
  }
}

.categories-section {
  .categories-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
  }

  .category-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .category-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 20px 0 20px;

      .category-icon {
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
      }

      .favorite-btn {
        color: #d1d5db;

        .favorited {
          color: #fbbf24;
        }
      }
    }

    .category-content {
      padding: 20px;

      .category-name {
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 10px 0;
      }

      .category-description {
        font-size: 14px;
        color: #6b7280;
        margin: 0 0 20px 0;
        line-height: 1.5;
      }

      .category-stats {
        display: flex;
        justify-content: space-around;
        margin-bottom: 20px;
        padding: 15px 0;
        background: #f8fafc;
        border-radius: 8px;

        .stat-item {
          text-align: center;

          .stat-value {
            display: block;
            font-size: 18px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 5px;
          }

          .stat-label {
            font-size: 12px;
            color: #6b7280;
          }
        }
      }

      .category-progress {
        display: flex;
        align-items: center;
        gap: 10px;

        .el-progress {
          flex: 1;
        }

        .progress-text {
          font-size: 12px;
          color: #6b7280;
          white-space: nowrap;
        }
      }
    }

    .category-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      background: #f8fafc;
      border-top: 1px solid #e5e7eb;

      .start-btn {
        font-weight: 600;
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-detail-modal {
  .category-detail-content {
    .detail-header {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #e5e7eb;

      .detail-icon {
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 28px;
        margin-right: 20px;
      }

      .detail-info {
        h3 {
          font-size: 24px;
          font-weight: 600;
          color: #1f2937;
          margin: 0 0 10px 0;
        }

        p {
          font-size: 16px;
          color: #6b7280;
          margin: 0;
        }
      }
    }

    .detail-stats {
      margin-bottom: 30px;

      .detail-stat {
        text-align: center;
        padding: 20px;
        background: #f8fafc;
        border-radius: 8px;

        .stat-number {
          font-size: 32px;
          font-weight: 700;
          color: #1f2937;
          margin-bottom: 10px;
        }

        .stat-label {
          font-size: 14px;
          color: #6b7280;
        }
      }
    }

    .detail-actions {
      display: flex;
      gap: 15px;
      justify-content: center;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .stats-overview {
    .el-col {
      margin-bottom: 15px;
    }
  }

  .filter-content {
    flex-direction: column;
    gap: 15px;

    .filter-left {
      margin-right: 0;
    }
  }

  .categories-grid {
    grid-template-columns: 1fr;
  }
}
</style>
